<style src="../../style/contentTable.css" scoped></style>
<template>
    <div class="containerTable">
        <Row class="divSearch">
            <Col span="24" >
            <!--根据需求删除不不要查询条件-->
            <label class="searchLabel">县&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(市):</label>
        <Select v-model="searchModel.AreaCode"  placeholder="请选择..." style="width: 100px" @on-change="getPageData()">
            <Option :value="userInfo.AreaCode">{{(userInfo.AreaCode=='530000000000')?'全省':'全市（州）'}}</Option>
            <Option :value="item.value" v-for="item in AreaList" :key="item.value">{{item.label}}</Option>
        </Select>
            <label class="searchLabel">填报年份：</label>
           
            <Select v-model="searchModel.FillInYear" placeholder="全部" :label-in-value="true" @on-change="getPageData()" style="width:120px">
              <Option value="">全部</Option>
                <Option v-for="yitem in yearList" :value="yitem.DictValue" :key="yitem.DictValue">{{ yitem.DictText }}</Option>
            </Select>
             <label class="searchLabel">季节类型：</label>
            <Select v-model="searchModel.TimesCycle" placeholder="全部" :label-in-value="true" @on-change="getPageData()" style="width:200px">
                <Option value="">全部</Option>
                <Option v-for="item in seasonList" :value="item.DictValue+'季度'" :key="item.DictValue">{{ item.DictText }}</Option>
            </Select>
            <label class="searchLabel">报表状态：</label>
            <Select v-model="searchModel.Status" placeholder="全部" :label-in-value="true" @on-change="getPageData()" style="width:120px">
               <Option value="">全部</Option>
                <Option v-for="uitem in statusList" :value="uitem.DictValue" :key="uitem.DictValue">{{ uitem.DictText }}</Option>
            </Select>           
            <!-- 报表状态：
            <Select v-model="searchModel.Status" placeholder="全部" :label-in-value="true" @on-change="getResult()" style="width:120px">
                <Option v-for="item in statusList" :value="item.DictValue" :key="item.DictValue">{{ item.DictText }}</Option>
            </Select> -->
            <Button icon="ios-search" type="ghost" @click="getPageData()">查询</Button>            
            <!-- <Button icon="ios-download" type="primary" @click="TmpDown()" style="float:right;margin-right:20px">模板下载</Button>        
            <Button icon="ios-download" type="primary" @click="ExcelDown()" style="float:right;margin-right:20px">数据导出</Button>
            <Upload :on-success="handleSuccess" :action="GetPostUrl()" style="float:right;margin-right:20px" v-show="DataModel.ReportStatus <3">
                <Button type="primary" icon="ios-cloud-upload-outline">数据导入</Button>
            </Upload> -->
            </Col>
        </Row>
        <Row>
            <Col span="24">
            <Table size="small"  :height="clientHeight" border :context="ctx" :columns="columnsList" :data="datas.rows" no-data-text='暂无数据...'></Table>
            </Col>
        </Row>
        <Row>
            <Col span="24">
            <Page class="page-style" :total="datas.total" placement="top" @on-change="getPageNumber" :page-size="searchModel.PageSize" :page-size-opts='pageSizeOpts' show-sizer @on-page-size-change="getPageSize" show-total show-elevator></Page>
            </Col>
        </Row>
        <Modal v-model="ViewShow" :mask-closable="false" width="1230" :styles="{top: '20px'}">
            <p slot="header" class="title">
                <Icon type="ios-paper" size="20"></Icon>
                <span style="font-size: 20px">{{ReportYear}}-{{AreaCodeName}}-主要水果生产情况季度统计表</span>
            </p>
            <p slot="close">
                <Icon type="close-circled" color="red" size=25></Icon>
            </p>            
            <table class="ContentTable" >  
              <thead>            
                <tr >                    
                    <th rowspan="2" >种类</th>
                    <th colspan="2" >在园面积（亩）</th>
                    <th >产量（吨）</th>
                    <th rowspan="2" >季度平均地头批发价（元/公斤）</th>
                    <th rowspan="2" >本季度新增面积（亩）</th> 
                    <th rowspan="2">备注</th>                   
                </tr>
                <tr>
                    <th >在园水果面积</th>
                    <th >已收获面积</th>
                    <th >已收获产量</th>                    
                </tr>
                </thead>
                <tbody>
                <tr v-for="(DataModel,index) in list">
                    <td v-if="DataModel.ParentCode" style="text-align:right;">{{DataModel.Variety}}</td> 
                    <td v-else style="font-weight:bold;">{{DataModel.Variety}}</td>                   
                    <td>
                      {{FormatBigNum(DataModel.ZyArea)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.YshArea)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.YshYield)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.AvgPrice)}}                            
                        </td> 
                        <td>
                          {{FormatBigNum(DataModel.AddArea)}}                            
                        </td>
                        <td>
                          {{DataModel.Remark}}
                        </td>                    
                </tr>
             </tbody>
             </table>          
            <div slot="footer" style="padding-bottom:50px">
              <div style="text-align:right;padding-top:5px">
                    <Button type="success" @click="toAlertCheckResult()" style="margin-right:50px">数据检测</Button>
                    <Button type="primary" @click="review('4','')">审核通过</Button>
                    <Button type="warning" @click="showAudit = true">退回重报</Button>
                </div>
                <Alert style="margin-top:5px;text-align:left" banner type="error">
                    填报时间：4月1日、7月1日、9月30日、12月31日</br>
                    填报说明: 1.全省范围内从乡（镇）起，逐级全面统计，由县级填报经州（市）审核后上报。
                    2.统计面积中不含育苗面积。
                    <span slot="desc">
                    </span>
                </Alert>
            </div>
        </Modal>
        <Modal v-model="showAudit" :mask-closable="false" width="500">
      <p slot="header" class="title">
        <Icon type="ios-paper" size="20"></Icon>
        <span style="font-size: 20px">退回重报原因</span>
      </p>
      <p slot="close">
        <Icon type="close-circled" color="red" size=25></Icon>
      </p>
      <Input v-model="strMsg" type="textarea" :rows="4" placeholder="请输入不通过原因..."></Input>
      <div slot="footer">
        <Button type="primary" @click="sureUnSure()">确定</Button>
        <Button type="ghost" @click="cancelUnSure()" style="margin-left: 8px">取消</Button>
      </div>
      </Modal>  
           <Modal v-model="showType" :mask-closable="false" width="1230" :styles="{top: '20px'}">
            <p slot="header" class="title">
                <Icon type="ios-paper" size="20"></Icon>
                <span style="font-size: 20px">{{ReportYear}}-{{AreaCodeName}}-主要水果生产情况季度统计表</span>
            </p>
            <p slot="close">
                <Icon type="close-circled" color="red" size=25></Icon>
            </p>            
            <table class="ContentTable" >  
              <thead>            
                <tr >                    
                    <th rowspan="2" >种类</th>
                    <th colspan="2" >在园面积（亩）</th>
                    <th >产量（吨）</th>
                    <th rowspan="2" >季度平均地头批发价（元/公斤）</th>
                    <th rowspan="2" >本季度新增面积（亩）</th>
                    <th rowspan="2" >备注</th>                      
                </tr>
                <tr>
                    <th >在园水果面积</th>
                    <th >已收获面积</th>
                    <th >已收获产量</th>                    
                </tr>
                </thead>
                <tbody>
                <tr v-for="(DataModel,index) in list">
                    <td v-if="DataModel.ParentCode" style="text-align:right;">{{DataModel.Variety}}</td> 
                    <td v-else style="font-weight:bold;">{{DataModel.Variety}}</td>                   
                    <td>
                      {{FormatBigNum(DataModel.ZyArea)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.YshArea)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.YshYield)}}                            
                        </td>
                        <td>
                          {{FormatBigNum(DataModel.AvgPrice)}}                            
                        </td> 
                        <td>
                          {{FormatBigNum(DataModel.AddArea)}}                            
                        </td>  
                        <td>
                          {{DataModel.Remark}}
                        </td>                   
                </tr>
             </tbody>
             </table>          
            <div slot="footer" style="padding-bottom:50px">              
                <Alert style="margin-top:5px;text-align:left" banner type="error">
                    填报时间：4月1日、7月1日、9月30日、12月31日</br>
                    填报说明: 1.全省范围内从乡（镇）起，逐级全面统计，由县级填报经州（市）审核后上报。
                    2.统计面积中不含育苗面积。
                    <span slot="desc">
                    </span>
                </Alert>
            </div>
        </Modal>      
    </div>
</template>
<script>
export default {
  data() {
    return {
      ReportYear:'',
      AreaCodeName:'',
      list: [],
      ViewShow: false, //编辑框弹出状态
      showType:false,
      reportId: "",
      strMsg:'',//不通过原因      
      showAudit:false,//不通过原因编辑框
      ruleValidate: {
        //验证模型
        ReportId: [
          { required: true, message: "填报基_报表编号不能为空", trigger: "blur" }
        ],
        Variety: [{ required: true, message: "种类不能为空", trigger: "blur" }],
        ZyArea: [{ required: true, message: "在园水果面积(亩）不能为空", trigger: "blur" }],
        YshArea: [{ required: true, message: "已收获面积（亩）不能为空", trigger: "blur" }],
        YshYield: [
          { required: true, message: "已收获产量（吨）不能为空", trigger: "blur" }
        ],
        AvgPrice: [
          { required: true, message: "季度平均地头批发价（元/公斤）不能为空", trigger: "blur" }
        ],
        AddArea: [
          { required: true, message: "本季度新增面积（亩）不能为空", trigger: "blur" }
        ]
      },
      userInfo: this.GetlocaStorage("fruuserinfo"),
      AreaList: [],//所属行政区划数组,
      yearList: this.GetGroupDict("ReportYear"), //周期
      seasonList: this.GetGroupDict("QuarterCycleValue"), //季节类型列表
      statusList: this.GetGroupDict("ReportStatus"), //报表状态类型列表
      dataModel: {
        //编辑模型
        Id: 0,
        ReportId: "",
        Variety: "",
        ZyArea: "",
        YshArea: "",
        YshYield: "",
        AvgPrice: "",
        AddArea: ""
      },
      clientHeight: window.innerHeight - 260, //表格默认高度
      //查询模型：根据需求删除不不要查询条件
      searchModel: {
        Id: "",
        ReportId: "",
        Variety: "",
        ZyArea: "",
        YshArea: "",
        YshYield: "",
        AvgPrice: "",
        AddArea: "",
        ReportCode: "FruProSeason",
        FillInYear: new Date().getFullYear() + "",
        TimesType: "",
        TimesCycle:"4季度",
        AreaCode: this.GetlocaStorage("fruuserinfo").AreaCode,
        Status:'',
        PageNumber: 1,
        PageSize: 20
      },
      pageSizeOpts: [20, 40, 50], //默认分页最大设置
      datas: {}, //table数据对象
      dataIds: [],
      ctx: this, //table数据上下文
      columnsList: [
        //表头对象
        // { type: 'selection', width: 60, align: 'center' },//多选设置
        { title: "报表名称", key: "ReportName" },
        { title: "所属行政区划", key: "AreaCodeName", width: 150 },
        //{ title: "填报年度", key: "FillInYear", width: 150 },
        //{ title: "填报周期", key: "TimesCycle", width: 150 },
        {
          title: "报表状态",
          key: "StatusName",
          width: 150,
          render: (h, params) => {
            switch (params.row.Status * 1) {
              case 0:
                return h(
                  "span",
                  { style: { color: "#ed3f14" } },
                  params.row.StatusName
                );
              case 1:
                return h(
                  "span",
                  { style: { color: "#ff9900" } },
                  params.row.StatusName
                );
              case 2:
                return h(
                  "span",
                  { style: { color: "#993300" } },
                  params.row.StatusName
                );
              case 3:
                return h(
                  "span",
                  { style: { color: "#2d8cf0" } },
                  params.row.StatusName
                );
              case 4:
                return h(
                  "span",
                  { style: { color: "#19be6b" } },
                  params.row.StatusName
                );
              case 5:
                return h(
                  "span",
                  { style: { color: "#80848f" } },
                  params.row.StatusName
                );
              default:
                return h(
                  "span",
                  { style: { color: "#ff9900" } },
                  params.row.StatusName
                );
            }
          }
        },
        // { title: "未通过原因", key: "Opinion" },
        { title: "填报时间", key: "StrUpdateTime", width: 180 },
        {
          title: "操作",
          key: "Id",
          width: 360,
          align: "center",
          render: (h, params) => {
            return h("div", [              
              h('Button', {
                class: {
                  ieditColor: true
                },
                props: {
                  size: 'small',
                  type: 'ghost',
                  icon: 'ios-paper-outline'
                }, style: {
                  marginRight: '5px'
                }, on: {
                  click: () => {
                    this.ReportYear = params.row.FillInYear;
                    this.AreaCodeName = params.row.AreaCodeName;
                    this.showInfo(params.row.Id, params.row.ReportCode)
                  }
                }
              }, '查看'),
              h('Button', {
                class: {
                  ieditColor: true
                },
                props: {
                  size: 'small',
                  type: 'ghost',
                  icon: 'network'
                }, style: {
                  marginRight: '5px'
                }, on: {
                  click: () => {
                    this.ReportYear = params.row.FillInYear;
                    this.AreaCodeName = params.row.AreaCodeName;
                    this.editInfo(params.row.Id, params.row.ReportCode)
                  }
                },
                attrs: {
                  disabled: params.row.Status == 3 ? false : true
                }
              }, '审核'),
              h('Button', {
                class: {
                  ieditColor: true
                },
                props: {
                  size: 'small',
                  type: 'ghost',
                  icon: 'ios-undo'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.unReview(params.row.Id)
                  }
                },
                attrs: {
                  disabled: params.row.Status == 4 ? false : true
                },
                directives: [
                  {
                    name: 'omg-operation',
                    value: { op: "unreview" }
                  }
                ],
              }, '取消审核'),
            ]);
          }
        }
      ]
    };
  },
  mounted() {
    //table高度计算方法
    const that = this;
    window.onresize = () => {
      return (() => {
        that.clientHeight = window.innerHeight - 260;
      })();
    };
  },
  methods: {
    //初始化行政区划树
        SearchAreaList() {
            var areaCode = this.userInfo.AreaCode;
            // console.log(areaCode);
            var areaList=[];
            if (areaCode != '530000000000' && areaCode != null) {
                var item = this.GetlocaStorage("areatreelist")[0];
                for (var i = 0; i < item.children.length; i++) {
                    if (item.children[i].value == areaCode) {
                        areaList.push(item.children[i]);
                    }
                }
            } else {

                areaList = this.GetlocaStorage("areatreelist");
            }
             this.AreaList=areaList[0].children;
        },
    //获取当前页码
    getPageNumber(pageIndex) {
      this.searchModel.PageNumber = pageIndex;
      this.getPageData();
    },
    //获取当前分页大小
    getPageSize(pageSize) {
      this.searchModel.PageSize = pageSize;
      this.getPageData();
    },
    //获取this.datas: {},//table数据对象
    getPageData() {
      var self = this;
      var user = this.GetlocaStorage("fruuserinfo");
//      this.searchModel.AreaCode = user.AreaCode;
      self.$http
        .post("Report/PostReviewPageList", this.searchModel)
        .then(function(res) {
          if (res.data.status === 1) {
            self.datas = res.data;
          } else {
            self.$Modal.error({ title: "提示信息", content: res.data.message });
          }
        });
    },
    //编辑获取对象传入id
    editInfo(id, reportCode) {
      //编辑
      this.reportId = id;
      var self = this;
      this.$http
        .get("Report", { params: { id: id, reportCode: reportCode } })
        .then(function(res) {
          if (res.data.list.status == 1) {
            self.list = res.data.list.model;
            self.ViewShow = true; //打开modal
          } else {
            self.$Modal.error({ title: "提示信息", content: "编辑数据加载失败!!!" });
          }
        });
    },
    showInfo(id, reportCode) {
      //编辑
      this.reportId = id;
      var self = this;
      this.$http
        .get("Report", { params: { id: id, reportCode: reportCode } })
        .then(function(res) {
          if (res.data.list.status == 1) {
            self.list = res.data.list.model;
            self.showType = true; //打开modal
          } else {
            self.$Modal.error({ title: "提示信息", content: "数据加载失败!!!" });
          }
        });
    },
    unReview(reportId){
        this.reportId = reportId;
        this.review("0","省级已取消审核");
    },
    //审核方法
    review(reportType,strMsg) {
      var self = this;     
      let obj = new Object();
      obj.Id = this.reportId;
      obj.reportType = reportType;
      obj.strMsg = strMsg;
          this.$http.post("Report/PostUpStatus", obj).then(function(res) {
            if (res.data.status == 1) { 
              self.strMsg = '';   
              if(self.ViewShow){
                self.ViewShow = false;
              }          
              self.getPageData();
              self.$Notice.success({ title: "操作成功！", desc: false });
            } else {
              self.$Modal.warning({
                title: "提示信息",
                content: "操作失败,请与管理员联系!"
              });
            }
          });
      
    },
    sureUnSure(){      
      this.showAudit = false;
      this.review("0",this.strMsg);
    },
    cancelUnSure(){
      this.strMsg = '';
      this.showAudit = false;
    },
    //数据检测
    checkData(){
     let templist = this.list;
     let isOk = true;//数据无误
     let sumObj = templist[templist.length-1];//合计栏数据
     let totalModel = new Object();
     totalModel.ZyArea = 0;
     totalModel.YshArea = 0;
     totalModel.YshYield = 0;
     totalModel.AddArea = 0;  
     for(let i = 0;i < templist.length;i++){
       let item  = templist[i];
       let parentModel = new Object();
       parentModel.ZyArea = 0;
       parentModel.YshArea = 0;
       parentModel.YshYield = 0;
       parentModel.AddArea = 0; 
       parentModel.hasChild = false; 
       for(let j = 0;j < templist.length;j++){
        let sonItem = templist[j];
        if(sonItem.ParentCode == item.VarietyCode){
          parentModel.hasChild = true;
          if(sonItem.ZyArea){
            parentModel.ZyArea += sonItem.ZyArea;
          }
          if(sonItem.YshArea){
            parentModel.YshArea += sonItem.YshArea;
          }
          if(sonItem.YshYield){
            parentModel.YshYield += sonItem.YshYield;
          }
          if(sonItem.AddArea){
            parentModel.AddArea += sonItem.AddArea;
          }
        }
       }
       if(parentModel.hasChild){        
       if(item.ZyArea && parentModel.ZyArea > item.ZyArea){         
         isOk = false;
         return item.Variety+'的在园面积不能小于其子项之和！';        
       }
       if(item.YshArea && parentModel.YshArea > item.YshArea){
         isOk = false;
         return item.Variety+'的已收获面积不能小于其子项之和！';
       }
       if(item.YshYield && parentModel.YshYield > item.YshYield){
         isOk = false;
         return item.Variety+'的已收获产量不能小于其子项之和！';
       }
       if(item.AddArea && parentModel.AddArea > item.AddArea){
         isOk = false;
        return item.Variety+'的季度新增面积不能小于其子项之和！';
       }   
       }    
       if(item.VarietyCode !='sum'&& !item.ParentCode){        
         if(item.ZyArea){
           totalModel.ZyArea += item.ZyArea;
         }
         if(item.YshArea){
           totalModel.YshArea += item.YshArea;
         }
         if(item.YshYield){
           totalModel.YshYield += item.YshYield;
         }
         if(item.AddArea){
           totalModel.AddArea += item.AddArea;
         }
       }
     }
     if(sumObj.ZyArea && (totalModel.ZyArea-sumObj.ZyArea < -1||totalModel.ZyArea-sumObj.ZyArea>1)){       
       isOk = false;
       return '合计栏的在园面积计算错误！';
     }
     if(sumObj.YshArea && (totalModel.YshArea-sumObj.YshArea < -1||totalModel.YshArea-sumObj.YshArea >1)){
       isOk = false;
       return '合计栏的已收获面积计算错误！';
     }
     if(sumObj.YshYield && (totalModel.YshYield-sumObj.YshYield < -1||totalModel.YshYield-sumObj.YshYield >1)){
       isOk = false;
       return '合计栏的已收获产量计算错误！';
     }
     if(sumObj.AddArea && (totalModel.AddArea-sumObj.AddArea < -1||totalModel.AddArea-sumObj.AddArea > 1)){
       isOk = false;
       return '合计栏的季度新增面积计算错误！';
     }
     if(isOk){
       return '数据检测无误！';
     }
     return '';
    },
    toAlertCheckResult(){ 
      var message  = this.checkData();   
      this.$Modal.warning({
        title:'提示信息',
        content:message
      });
    },
    
    //编辑框打开
    modalShow() {
      this.ViewShow = true;
    },
    //编辑框关闭
    modalHide() {
      this.ViewShow = false;
    },
    //取消方法
    cancel() {
      this.ViewShow = false;
    },
    //重置model
    restModel(modelname) {
      this.$refs[modelname].resetFields(); //重置model
    },
    CurrentSeason(){
      var self = this;
      let currentMonth = new Date().getMonth()+1;      
      if(currentMonth >= 2 &&currentMonth <= 5){
        self.searchModel.TimesCycle = "1季度";
      }
      else if(currentMonth >= 6&&currentMonth <= 8){
        self.searchModel.TimesCycle = "2季度";
      }
      else if(currentMonth >= 9&&currentMonth <= 11){
        self.searchModel.TimesCycle = "3季度";
      }
      else{
        self.searchModel.TimesCycle = "4季度";
      }
      
    },
    currentYear() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth();
      if (month > 1) {
        this.searchModel.FillInYear = year.toString();
      } else {
        this.searchModel.FillInYear = (year - 1).toString();
      }
    }
  },
  //创建Vue页面方法
  created: function() {
    //创业Vue前调用获取this.datas: {},//table数据对象
    this.currentYear();
    this.CurrentSeason();
    this.getPageData();
    this.SearchAreaList();
  },
  watch: {
    //需要监听的在此处新增监听对象
  }
};
</script>
